#!/bin/sh

socket=0
tmppath="$XDG_CACHE_HOME"
if [ -z "$tmppath" ]; then
    tmppath="$HOME/.cache"
fi
tmppath="$tmppath/orbital"
mkdir -p $tmppath >/dev/null

configpath="$XDG_CONFIG_HOME"
if [ -z "$configpath" ]; then
    configpath="$HOME/.config"
fi
configpath="$configpath/orbital"
mkdir -p $configpath > /dev/null

while getopts S:v name
do
    case $name in
        S)  if [ $OPTARG -eq $OPTARG 2> /dev/null ]; then
                socket="$OPTARG"
            else
                echo "Invalid socket number. Must be an integer."
                exit 1
            fi;;
        v)  echo "Version: 0.1"
            exit 0;;
        ?)  printf "Usage: %s: [-Svalue]\n" $0
            exit 2;;
    esac
done

logfile="$tmppath/orbital-$socket.log"
out="$tmppath/orbital-$socket.out"
err="$tmppath/orbital-$socket.err"

function watch() {
    IFS=''
    while read a; do
        echo "$a"
        echo "$2$a" >>$logfile
    done < "$1"
}

rm $logfile $out $err > /dev/null 2>&1
mkfifo $out $err
trap 'rm "$out" "$err"' EXIT

exec 4<>"$out"
exec 5<>"$err"

(watch "$out" "stdout: " >&1) &
pidout=$!
(watch "$err" "stderr: " >&2) &
piderr=$!

exec 1>&4
exec 2>&5

plugin="@Nuclear_PREFIX@/lib/nuclear-shell/nuclear-desktop-shell.so"
if [ "@Nuclear_VERSION@" == "0.0.1" ]; then
    plugin="@Nuclear_PREFIX@/lib/nuclear-shell/nuclear-shell.so"
fi
args="--shell=$plugin --nuclear-client=@CMAKE_INSTALL_PREFIX@/libexec/startorbital --session-file=$configpath/session -Swayland-$socket"

if [ -z "$DBUS_SESSION_BUS_ADDRESS" ] && type dbus-launch >/dev/null; then
    eval `dbus-launch --sh-syntax`
fi

export QT_QPA_PLATFORM="wayland"
export XDG_CURRENT_DESKTOP="orbital"

if [ -z "$DISPLAY" ]; then
    stdbuf -oL -eL weston-launch -- $args
else
    stdbuf -oL -eL weston $args
fi

if [[ $DBUS_SESSION_BUS_PID ]]; then
    kill $DBUS_SESSION_BUS_PID
fi

kill $pidout
kill $piderr
